package top.yifengxiner.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import org.springframework.stereotype.Component;
import top.yifengxiner.common.exception.JwtException;

import java.util.Date;

/**
 * @author ：baixiao
 * @date ：Created in 2021/5/7 11:13
 * @description：token工具类
 * @modified By：
 * @version: 0.0.1$
 */
@Component
public class TokenUtils
{

    private static final long EXPIRE_TIME = 1*60*60;

    /*自定义密钥*/
    private static final String SECRET_KEY = "jwt_secret";

    /**
     * 生成token
     * @param subject
     * @return
     */
    public static String createToken(String subject)
    {
        String token = "";
        token = JWT.create()
                .withIssuedAt(new Date()) //签发时间
                .withSubject("subject") //面向用户
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_TIME)) //到期时间
                .withAudience(subject) //签发对象
                .withClaim("subject",subject) //负载签发对象
                .sign(Algorithm.HMAC256(SECRET_KEY)); //签发密钥
        return token;
    }

    /**
     * 验证token
     * @param token
     * @return
     */
    public static Boolean verifyToken(String token)
    {
        JWTVerifier verifier = JWT
                .require(Algorithm.HMAC256(SECRET_KEY))
                .acceptExpiresAt(EXPIRE_TIME)
                .build();
        try
        {
            verifier.verify(token);
        }
        catch (JWTVerificationException e)
        {
            return false;
        }
        return true;
    }

    /**
     * 通过token解析出签发对象
     * @return
     */
    public static String getSubject(String token)
    {
        Claim claim = JWT.decode(token).getClaim("subject");
        System.out.println(claim.asString());
        return claim.asString();
    }
}
